import { Button, View } from '@tarojs/components';
import {
  hideLoading,
  navigateTo,
  showLoading,
  stopPullDownRefresh,
  useDidShow,
  usePullDownRefresh,
  useReachBottom,
  useRef,
  useState,
  showToast
} from '@tarojs/taro';
import dayjs from 'dayjs';
import Layout from '../../components/Layout';
import Empty from '../../components/Result/Empty';
import XList from '../../components/XList';
import XRow from '../../components/XRow';
import XTab from '../../components/XTab';
import { CacheTempProductId } from '../../constant/cache';
import { bugStatus, priObject } from '../../constant/label';
import baseService from '../../utils/baseService';
import { getCache } from '../../utils/utils';
import './css/index.less';

const Workb = () => {
  const [bug, setBug] = useState({});
  const [rows, setRows] = useState([]);
  const [users, setUsers] = useState({});
  const pageIndex = useRef(1);
  const productIdRef = useRef(null);
  const tabActiveIndex = useRef(0);
  const tabOptions = ['指给我的', '我创建的', '我解决的'];

  useDidShow(() => {
    const tempProductId = getCache(CacheTempProductId, true);
    if (tempProductId) {
      productIdRef.current = tempProductId;
      pageIndex.current = 1;
    }
    getRows();
  });

  usePullDownRefresh(() => {
    pageIndex.current = 1;
    getRows(() => {
      stopPullDownRefresh();
    });
  });

  useReachBottom(() => {
    if (bug['pager']['pageTotal'] > pageIndex.current) {
      pageIndex.current++;
      getRows();
    }
  });

  const getRows = (cb = null) => {
    const tps = { 0: 'assignedTo', 1: 'openedBy', 2: 'resolvedBy' };
    const url =
      '/my-bug-' +
      tps[tabActiveIndex.current] +
      '-openedDate_desc--10-' +
      pageIndex.current +
      '.json';
    showLoading({ title: '操作中' });
    baseService
      .query(url, {})
      .then(({ status, data = {} }) => {
        console.log(data);
        const { bugs = [], users = {} } = data;
        setRows(pageIndex.current === 1 ? bugs : rows.concat(bugs));
        setUsers(users);
        setBug(data);
        hideLoading();
        cb && cb();
      })
      .catch(() => {
        showToast({ title: '查询失败', icon: 'none' });
        hideLoading();
      });
  };

  const onRedirect = (url) => {
    navigateTo({ url });
  };

  const onRemove = () => {
    productIdRef.current = null;
    pageIndex.current = 1;
    getRows();
  };

  const onChangeTab = (index) => {
    tabActiveIndex.current = index;
    pageIndex.current = 1;
    getRows();
  };

  return (
    <Layout>
      <View
        className="issues-icon"
        onClick={onRedirect.bind(this, 'search')}
        style={{ bottom: '130px' }}
      >
        搜BUG
      </View>
      <View
        className="issues-icon"
        onClick={onRedirect.bind(this, 'edit')}
        style={{ fontSize: '36px', lineHeight: '55px', alignItems: 'inherit' }}
      >
        +
      </View>
      <XTab options={tabOptions} onChange={onChangeTab}></XTab>
      <View>
        {!rows.length && <Empty></Empty>}
        {rows.map((x) => (
          <XList
            arrow="right"
            isCustomize={true}
            key={x.id}
            style={{ padding: '8px 10px 8px 15px', marginBottom: '4px', fontSize: '14px' }}
            onClick={onRedirect.bind(this, 'detail?id=' + x['id'])}
          >
            <XRow>{x['title']}</XRow>
            <XRow style={{ fontSize: '12px', color: '#8c8c8c' }}>
              <XRow>
                <View
                  style={{
                    marginRight: '5px'
                  }}
                >
                  #{x['id']}
                </View>
                <View style={{ color: bugStatus[x['status']].color, marginRight: '5px' }}>
                  {bugStatus[x['status']].label}
                </View>
                <View style={{ color: priObject[x['pri']].color, marginRight: '5px' }}>
                  {priObject[x['pri']].label}
                </View>
              </XRow>
              最近修改：
              {`${
                x['lastEditedBy']
                  ? users[x['lastEditedBy']] || x['lastEditedBy']
                  : users[x['openedBy']] || x['openedBy']
              } ${
                x['lastEditedBy']
                  ? dayjs(x['lastEditedDate']).format('MM-DD HH:mm')
                  : dayjs(x['openedDate']).format('MM-DD HH:mm')
              }`}
            </XRow>
          </XList>
        ))}
      </View>
    </Layout>
  );
};
Workb.config = { navigationBarTitleText: 'Bug管理', enablePullDownRefresh: true };
export default Workb;
